package com.mydemo.admin.controller;

import com.mydemo.admin.service.ISysRoleService;
import com.mydemo.common.annotation.Log;
import com.mydemo.common.penum.BusinessType;
import com.mydemo.common.pojo.RespResult;
import com.mydemo.common.pojo.Role;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author Last_Island
 * @version 1.0
 */
@RestController
@RequestMapping("/role")
public class SysRoleController extends BaseController{

    @Autowired
    private ISysRoleService sysRoleService;

    /**
     * 获取角色列表
     * @param role 查询条件
     * @return
     */
    @PreAuthorize("@authz.decide('system:role:list')")
    @GetMapping("/list")
    public RespResult getList(Role role) {
        startPage();
        List<Role> roleList = sysRoleService.getRoleList(role);
        return getTabData(roleList);
    }

    /**
     * 添加角色
     * @param role 角色信息
     * @return
     */
    @PreAuthorize("@authz.decide('system:role:add')")
    @PostMapping
    @Log(title = "角色管理", businessType = BusinessType.INSERT)
    public RespResult addRole(@RequestBody Role role) {
        return sysRoleService.addRole(role) ? RespResult.defaultSuccess() : RespResult.defaultError();
    }

    /**
     * 删除角色
     * @param roleId 角色ID
     * @return
     */
    @PreAuthorize("@authz.decide('system:role:del')")
    @DeleteMapping("/{roleId}")
    @Log(title = "角色管理", businessType = BusinessType.DELETE)
    public RespResult deleteRole(@PathVariable("roleId") Long roleId) {
        return sysRoleService.deleteRole(roleId) ? RespResult.defaultSuccess() : RespResult.defaultError();
    }

    /**
     * 更新角色
     * @param role 角色信息
     * @return
     */
    @PreAuthorize("@authz.decide('system:role:update')")
    @PutMapping
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    public RespResult updateRole(@RequestBody Role role) {
        return sysRoleService.updateRole(role) ? RespResult.defaultSuccess() : RespResult.defaultError();
    }

    /**
     * 根据角色ID获取角色信息
     * @param roleId 角色ID
     * @return
     */
    @PreAuthorize("@authz.decide('system:role:get')")
    @GetMapping("/{roleId}")
    public RespResult getRoleById(@PathVariable("roleId") Long roleId) {
        Role role = sysRoleService.getRoleByRoleId(roleId).get(0);
        role.getPermissions().forEach(permission -> permission.setAuthority(null));
        return RespResult.defaultSuccess(role);
    }
}
